package com.xxl.job.admin.controller;

import com.xxl.job.admin.controller.annotation.PermessionLimit;
import com.xxl.job.admin.controller.interceptor.PermissionInterceptor;
import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.util.CookieUtil;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.service.XxlJobService;
import com.xxl.job.core.biz.model.ReturnT;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
/**
 * 主页面
 * index controller
 * @author xuxueli 2015-12-19 16:13:16
 */
@Controller
public class IndexController {

	@Resource
	private XxlJobService xxlJobService;
	@Autowired
	private XxlJobAdminConfig xxlJobAdminConfig;

	
	
	@RequestMapping("/")
	public String index(Model model) {
		/**
		 * 主页面包含元素： 执行器数量，job数量，累计调度数量，成功数量
		 */
		Map<String, Object> dashboardMap = xxlJobService.dashboardInfo();
		model.addAllAttributes(dashboardMap);
		return "index";
	}

    @RequestMapping("/chartInfo")
	@ResponseBody
	public ReturnT<Map<String, Object>> chartInfo(Date startDate, Date endDate) {
    	/**
    	 * 调度报表 [开始日期-结束日期内]：
    	 * 		日期分布图：成功，失败，进行中
    	 * 		调度成功总数量，成功数量，失败数量
    	 */
        ReturnT<Map<String, Object>> chartInfo = xxlJobService.chartInfo(startDate, endDate);
        return chartInfo;
    }
	
    
	@RequestMapping("/toLogin")
	@PermessionLimit(limit=false)
	public String toLogin(Model model, HttpServletRequest request) {
		if (ifLogin(request)) {
			return "redirect:/";
		}
		return "login";
	}
	@RequestMapping(value="login", method=RequestMethod.POST)
	@ResponseBody
	@PermessionLimit(limit=false)
	public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response, String userName, String password, String ifRemember){
		// valid
		if (ifLogin(request)) {
			return ReturnT.SUCCESS;
		}

		// param
		if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)){
			return new ReturnT<String>(500, I18nUtil.getString("login_param_empty"));
		}
		boolean ifRem = (StringUtils.isNotBlank(ifRemember) && "on".equals(ifRemember))?true:false;

		// do login
		boolean loginRet = login(response, userName, password, ifRem);
		if (!loginRet) {
			return new ReturnT<String>(500, I18nUtil.getString("login_param_unvalid"));
		}
		return ReturnT.SUCCESS;
	}
	@RequestMapping(value="logout", method=RequestMethod.POST)
	@ResponseBody
	@PermessionLimit(limit=false)
	public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response){
		if (ifLogin(request)) {
			doLogout(request, response);
		}
		return ReturnT.SUCCESS;
	}
	
	
	@RequestMapping("/help")
	public String help() {
		//使用教程
		return "help";
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	
	private final boolean login(HttpServletResponse response, String username, String password, boolean ifRemember){
    	// login token
		String tokenTmp = DigestUtils.md5Hex(username + "_" + password);
		tokenTmp = new BigInteger(1, tokenTmp.getBytes()).toString(16);

		if (!xxlJobAdminConfig.getLOGIN_IDENTITY_TOKEN().equals(tokenTmp)){
			return false;
		}

		// do login
		CookieUtil.set(response,PermissionInterceptor.LOGIN_IDENTITY_KEY,xxlJobAdminConfig.getLOGIN_IDENTITY_TOKEN(), ifRemember);
		return true;
	}
	private void doLogout(HttpServletRequest request, HttpServletResponse response){
		CookieUtil.remove(request, response,PermissionInterceptor.LOGIN_IDENTITY_KEY);
	}
	private boolean ifLogin(HttpServletRequest request){
		String indentityInfo = CookieUtil.getValue(request,PermissionInterceptor.LOGIN_IDENTITY_KEY);
		if (indentityInfo==null || !xxlJobAdminConfig.getLOGIN_IDENTITY_TOKEN().equals(indentityInfo.trim())) {
			return false;
		}
		return true;
	}
}